package cn.tedu.fresheveryday.exception.handler;

import cn.tedu.fresheveryday.exception.ServiceException;
import cn.tedu.fresheveryday.restful.JsonResult;
import cn.tedu.fresheveryday.restful.ResponseCode;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 处理Exception
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public JsonResult<Void> handlerException(Exception e) {
        e.printStackTrace();

        return JsonResult.error(ResponseCode.ERROR, e);
    }

    /**
     * 处理ServiceException
     * @param e
     * @return
     */
    @ExceptionHandler(ServiceException.class)
    public JsonResult<Void> handlerServiceException(ServiceException e) {
        e.printStackTrace();

        return JsonResult.error(e.getResponseCode(), e);
    }

    /**
     * 处理BindException
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    public JsonResult<Void> handlerBindException(BindException e) {
        e.printStackTrace();

        BindingResult bindingResult = e.getBindingResult();
        FieldError fieldError = bindingResult.getFieldError();
        String defaultMessage = fieldError.getDefaultMessage();

        return JsonResult.error(ResponseCode.BAD_REQUEST, defaultMessage);
    }

}